<script setup>
import { fetch24HourData } from '../api/weatherAPI'
import * as echarts from 'echarts'
import { useCityStore } from '../stores/cityStore'
import { ref, watch, onMounted } from 'vue'
import dayjs from 'dayjs' //引入dayjs日期库

const hour24 = ref([])
//声名两个变量分别存放预报时间和温度
const hour24FxTime = ref([]) //时间
const hour24Temp = ref([]) //温度
const updateTime = ref('') //天气更新时间
const chartDom = ref(null) //1.vue3中引入dom元素的方式，声名一个引用
const cityStore = useCityStore()
let myChart = null

const initChart = () => {
  if (myChart) {
    myChart.dispose()
  }
  myChart = echarts.init(chartDom.value)
}

const updateChart = (hours, temps) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: '{b}时: {c}°C',
    },
    grid: {
      left: '10%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: hours,
      axisLine: {
        lineStyle: {
          color: '#666',
        },
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#666',
        },
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
        formatter: '{value}°C',
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
        },
      },
    },
    series: [
      {
        name: '温度',
        type: 'bar',
        barWidth: '40%',
        data: temps,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#0077e6' },
          ]),
          borderRadius: [4, 4, 0, 0],
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          shadowBlur: 4,
          shadowOffsetY: 2,
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#ff9a45' },
              { offset: 0.5, color: '#ff6a00' },
              { offset: 1, color: '#ff4500' },
            ]),
          },
        },
      },
    ],
  }
  myChart.setOption(option)
}

const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

//添加监听器，监听状态管理中location状态的变化
watch(
  //监听数据源
  () => cityStore.location,
  //回调函数
  () => {
    getData(cityStore.location.id)
  },
  //即时回调
  { immediate: true }
)

async function getData(locationID) {
  try {
    const res = await fetch24HourData(locationID)
    updateTime.value = dayjs(res.updateTime).format('YYYY年MM月DD日 HH时mm分')
    hour24.value = res.hourly

    hour24FxTime.value = []
    hour24Temp.value = []

    hour24.value.forEach((element) => {
      hour24FxTime.value.push(element.fxTime)
      hour24Temp.value.push(element.temp)
    })

    const formattedHours = hour24FxTime.value.map((x) => dayjs(x).format('HH'))

    if (!myChart) {
      initChart()
    }
    updateChart(formattedHours, hour24Temp.value)
  } catch (error) {
    console.error('获取24小时天气数据失败:', error)
  }
}
</script>

<template>
  <div class="weather-container">
    <!-- {{hour24}} -->
    <h3>未来24小时天气预报</h3>
    <div class="update-time">
      <span>最后更新时间：{{ updateTime }}</span>
    </div>
    <!-- 添加图表库需要的容器 -->
    <!-- 2.添加ref属性与1.进行绑定 -->
    <div class="chart-container" ref="chartDom"></div>
  </div>
</template>

<style scoped>
.weather-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 300px;
  margin-top: 15px;
}

h3 {
  text-align: center;
  color: #333;
  margin-bottom: 10px;
  font-size: 16px;
}

.update-time {
  text-align: center;
  color: #666;
  font-size: 12px;
  margin-bottom: 15px;
}
</style>